package dao;

import hibernate.HibernateUtil;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Dao {
	
	private static Dao instance;
	private Session session;
	
	private Dao(){
		
	}
	
	public static Dao getInstance(){
		if(instance==null)
			instance = new Dao();
		return instance;
	}
	
	public <T> void salvarObjeto(T object){
		try{
			session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			session.save(object);
			tx.commit();
		}catch(Exception e){
			
		}finally{
			session.close();
		}
	}
	
	public <T> Object buscarObjetoChavePrimaria(Long primaria, Class<T> clazz){
		try{
			session = HibernateUtil.getSession();
			Object obj = session.get(clazz, primaria);
			return obj;
		}catch(Exception e){
			return null;
		}finally{
			session.close();
		}
	}
	
	public <T> Object criarQuery(String query){
		try{
			session = HibernateUtil.getSession();
			Object obj = session.createQuery(query).uniqueResult();
			return obj;
		}catch(Exception e){
			return null;
		}finally{
			session.close();
		}
	}
	
	public <T> void removerObjeto(T object){
		try{
			session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			session.delete(object);
			tx.commit();
		}catch(Exception e){
			
		}finally{
			session.close();
		}
	}
	
	public <T> void atualizarObjeto(T object){
		try{
			session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			session.update(object);
			tx.commit();
		}catch(Exception e){
			
		}finally{
			session.close();
		}
	}
	
	public List<?> listarObjetos(Class<?> classe){
		try{
			session = HibernateUtil.getSession();
			Criteria criteria = session.createCriteria(classe);
			return criteria.list();
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			session.close();
		}
	}

}
